import React, { useState, useEffect, useRef } from 'react';

function Countdown({ targetDate }) {
    const targetTime = useRef(new Date(targetDate).getTime());

    const calculateTimeLeft = () => {
        let difference = targetTime.current - Date.now();
        if (difference <= 0) {
            return { days: 0, hours: 0, minutes: 0, seconds: 0 };
        }

        // 计算剩余时间 (秒)
        let remainingSeconds = Math.round(difference / 1000);

        // 计算剩余天数
        let days = Math.floor(remainingSeconds / 86400);
        remainingSeconds = remainingSeconds % 86400;

        // 计算剩余小时
        let hours = Math.floor(remainingSeconds / 3600);
        remainingSeconds = remainingSeconds % 3600;

        // 计算剩余分钟
        let minutes = Math.floor(remainingSeconds / 60);
        remainingSeconds = remainingSeconds % 60;

        return {
            days,
            hours,
            minutes,
            seconds: remainingSeconds
        };
    };

    const [timeLeft, setTimeLeft] = useState(calculateTimeLeft());

    useEffect(() => {
        const timer = setInterval(() => {
            setTimeLeft(calculateTimeLeft());
        }, 1000);

        return () => clearInterval(timer);
    }, []);

    const formatTimeUnit = (timeUnit) => {
        return timeUnit < 10 ? (`0${timeUnit}`) : timeUnit;
    }

    return (
        <div>{formatTimeUnit(timeLeft.hours)}: {formatTimeUnit(timeLeft.minutes)}: {formatTimeUnit(timeLeft.seconds)}</div>
    );
}

export default function CountdownPage() {
    const targetDate = '2023-06-30T16:00:00.000Z';

    return (
        <>
            {/* <h1>秒杀活动倒计时</h1> */}
            <Countdown targetDate={targetDate} />
        </>
    );
}